package com.cctc.mychat.client.handler.heartbeat;

import com.cctc.mychat.common.protocol.message.impl.request.HeartBeatRequestMessage;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

import java.util.concurrent.TimeUnit;

public class HeartBeatRequestTimer extends ChannelInboundHandlerAdapter {
    private static final int HEARTBEAT_INTERVAL = 3;

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        scheduleHeartBeatRequestMessage(ctx);
    }

    private void scheduleHeartBeatRequestMessage(ChannelHandlerContext ctx) {
        sendHeartBeatRequestMessage(ctx);
        ctx.executor().schedule(() -> {
            if (ctx.channel().isActive()) {
                sendHeartBeatRequestMessage(ctx);
            }
        }, HEARTBEAT_INTERVAL, TimeUnit.SECONDS);
    }

    private void sendHeartBeatRequestMessage(ChannelHandlerContext ctx) {
        HeartBeatRequestMessage request = HeartBeatRequestMessage.builder().build();
        ctx.writeAndFlush(request);
    }
}
